package com.rc.saas.mini.common.upyun;

import com.UpYun;
import com.rc.saas.mini.common.config.UpYunConfig;
import com.upyun.UpException;

import java.io.IOException;

/**
 * https://github.com/upyun/java-sdk
 * 云存储基础接口
 * Created by sven on 2018-03-17
 */
public class UpYunSdk {
    private static UpYunSdk singleton = null;
    private UpYun upyun;

    private UpYunSdk(UpYunConfig upYunConfig) {
        // 创建实例,只能使用服务的操作员身份登录，而不是又拍云的登录帐号
        upyun = new UpYun(upYunConfig.getBucketName(), upYunConfig.getUserName(), upYunConfig.getPassword());

        //可选属性1，是否开启 debug 模式，默认不开启
        upyun.setDebug(true);
        //可选属性2，超时时间，默认 30s
        upyun.setTimeout(30);
    }

    /**
     * 懒汉式单例模式
     * @param upYunConfig
     * @return
     */
    public static UpYunSdk getInstance(UpYunConfig upYunConfig) {
        //如果不存在才真的创建实例
        if (singleton == null) {
            synchronized (UpYunSdk.class) {
                singleton = new UpYunSdk(upYunConfig);
            }
        }

        return singleton;
    }

    //private UpYunSdk(String bucketName, String userName, String password) {
    //    // 创建实例,只能使用服务的操作员身份登录，而不是又拍云的登录帐号
    //    upyun = new UpYun("jzimage", "sven", "jt201818");
    //
    //    //可选属性1，是否开启 debug 模式，默认不开启
    //    upyun.setDebug(true);
    //    //可选属性2，超时时间，默认 30s
    //    upyun.setTimeout(30);
    //}


    //public static UpYunUtil newInstance() {
    //    if (upYunUtil == null) {
    //        upYunUtil = new UpYunUtil();
    //    }
    //    return upYunUtil;
    //}

    /**
     * 创建目录
     * @param path
     * @return
     * @throws IOException
     * @throws UpException
     */
    public boolean mkDir(String path) throws IOException, UpException {
        return upyun.mkDir(path);
    }

    /**
     * 读取目录
     *
     * @return
     * @throws IOException
     * @throws UpException
     */
    //public List<UpYun.FolderItem> readDir() throws IOException, UpException {
    //    List<UpYun.FolderItem> items = upyun.readDir("/");
    //    return items;
    //}


    /**
     * 删除文件/up/tt/20180318/20181011095225.jpg
     *
     * @param uploadPath 文件在又拍云的路径,若 filePath 指定的文件不存在，则返回『文件不存在』的错误
     * @return
     * @throws IOException
     * @throws UpException
     */
    //public boolean deleteFile(String uploadPath) throws IOException, UpException {
    //    return upyun.deleteFile(uploadPath);
    //}

    // 删除目录
    //boolean result = upyun.rmDir('/up/tt/');
    public static void main(String[] args) throws IOException, UpException {
        //UpYunSdk upYunSdk = new UpYunSdk();
        //
        //boolean result = upYunSdk.mkDir("/8888");
        //System.out.println(result);
        //List<UpYun.FolderItem> list = upYunSdk.readDir();
        //System.out.println(list);
    }
}
